import React, { useRef, useEffect } from "react";
import { View } from '@tarojs/components'
import TabBar from "../../components/tabbar";
import Taro, { getMenuButtonBoundingClientRect, setStorage, removeStorageSync, eventCenter,useShareAppMessage } from "@tarojs/taro";
import { Image, Progress, Icon, Row, Col, Cell } from "@antmjs/vantui";
import { useState } from "react";
import { IconFont, CusCard, CusModal } from "../../components";
import GongZhongHao from "../../image/gongzhouhao.png"
import Xiaochengxu from "../../image/xiaochengxu.jpg"
import Wechat from "../../image/wechat.jpg"
import { getuserinfo } from "../../https/mine"
import { login } from '../../https/local';
import { checkLogin, getUserInfo, HOST, judgeLogin } from "../../utils/const";
import './index.scss'

const Mine = () => {
  const btn = getMenuButtonBoundingClientRect();
  const [imgUrl, setImgUrl] = useState(null)
  const [userInfo, setUerInfo] = useState(null)
  const [isLogin, setIsLogin] = useState(false)
  const modalRef = useRef()

  useEffect(() => {
    getLoginStatus()
    eventCenter.on("updateUserInfo", refeshUserInfo);

  }, [isLogin])

  useShareAppMessage((res) => {
    if (res.from === "button") {
      // 来自页面内分享按钮
    } else {
      // 右上角分享好友
    }

    return {
      title: "", // 分享卡片的title
      path: "", // 分享卡片的小程序路径
      imageUrl: "", // 分享卡片的图片链接
    };
  });


  const refeshUserInfo = () => {
    if (JSON.stringify(getUserInfo()) != '{}') {
      getuserinfo({ userId: getUserInfo()?.user_id }).then((res) => {
        Taro.hideLoading()
        if (res.success) {
          setUerInfo(res?.data)
          setStorage({
            key: 'USERINFO', data: JSON.stringify(res?.data), success: () => {
              setIsLogin(true)
            }
          })
        }
      })
    }
  }

  const getLoginStatus = () => {
    if (checkLogin()) {
      setIsLogin(true)
      setUerInfo(getUserInfo())
    } else {
      setIsLogin(false)
      setUerInfo(null)
    }
  }

  const myAccount = () => {
    return (
      <View>
        <Row gutter={'23'} className="line-bg-view">
          <Col span={'7'} className="row-item-view" onClick={() => {
            if (!judgeLogin()) {
              return Taro.showToast({ title: '请先登录', icon: 'error' })
            }
            Taro.navigateTo({ url: '/pages/mine/components/mycoins/index' })
          }}>
            <View className="title-view">{userInfo?.coin || 0}</View>
            <View className="subtitle-view">金币</View>
          </Col>
          <Col span={'1'} className="line-bg-view">
            <View className="line-view"></View>
          </Col>
          <Col span={'7'} className="row-item-view" onClick={() => {
            if (!judgeLogin()) {
              return Taro.showToast({ title: '请先登录', icon: 'error' })
            }
            Taro.navigateTo({ url: '/pages/mine/components/myfavorites/index' })
          }}>
            <View className="title-view">{userInfo?.collectionCnt || 0}</View>
            <View className="subtitle-view">收藏</View>
          </Col>
          <Col span={'1'} className="line-bg-view">
            <View className="line-view"></View>
          </Col>
          <Col span={'7'} className="row-item-view" onClick={() => {
            if (!judgeLogin()) {
              return Taro.showToast({ title: '请先登录', icon: 'error' })
            }
            Taro.navigateTo({ url: '/pages/mine/components/mytracks/index' })
          }}>
            <View className="title-view">{Taro.getStorageSync("footprint") ? JSON.parse(Taro.getStorageSync("footprint")).length : 0}</View>
            <View className="subtitle-view">足迹</View>
          </Col>
        </Row>
      </View>
    )
  }

  const onclickMyMaterial = () => {
    Taro.navigateTo({ url: '/pages/mine/components/mymaterial/index' })
  }

  const loginIn = () => {
    Taro.login({
      desc: '正在获取',//不写不弹提示框
      success: function (res) {
        console.log('code', res)
        login({ loginType: '001', code: res?.code }).then((res) => {
          if (res?.data?.id) {
            Taro.showLoading({ title: '加载中' })
            getuserinfo({ userId: res?.data?.id }).then((res) => {
              Taro.hideLoading()
              if (res.success) {
                setUerInfo(res?.data)
                setStorage({
                  key: 'USERINFO', data: JSON.stringify(res?.data), success: () => {
                    setIsLogin(true)
                  }
                })
              }
            })
          }
        })
      },
      fail: function (err) {
      }
    }
    )
  }

  return (
    <View className="mine-view">
      <View className="sub-box-view">
        <View onClick={() => {
          if (isLogin) {
            onclickMyMaterial()
          } else {
            loginIn()
          }
        }} style={{ paddingTop: btn.bottom + 20 }} className="user-info-view">
          {isLogin ? <Image width={160} height={160} radius={'50%'} src={userInfo?.avatar ? HOST + userInfo?.avatar : 'https://img.yzcdn.cn/vant/cat.jpeg'} /> :
            <IconFont name="ac-weidenglu" size={130} />}
          <View className="info-sub-view">
            <View className="name-text">{isLogin ? userInfo?.nickname : '点击登录'}</View>
            {/* <View className="lever-view">
              <View className="lever-text">{userInfo?.lever}</View>
              <View className="progress-text">{`${userInfo?.progress}/100`}</View>
            </View>
            <View className="progress-view">
              <Progress percentage={userInfo?.progress} strokeWidth="8" pivotText={<></>} />
            </View> */}
          </View>
          <View style={{ display: 'flex', justifyContent: 'flex-end', width: '20%' }}>
            <Icon name="arrow" size={40} color="#8D949D" />
          </View>
        </View>
        <View style={{ marginTop: 20 }}>
          <CusCard top_left_tit={'我的账户'}
            top_rightView={<></>
              // <View className="account-row-view" onClick={() => Taro.navigateTo({ url: '/pages/mine/components/adfree/index' })}>
              //   <View className="row-text">免广告权益</View>
              //   <Icon className="row-icon" name="arrow" size={30} color="#8D949D" />
              // </View>
            }
            children={myAccount()} />
        </View>
        <View style={{ marginTop: 20 }}>
          <CusCard top_left_tit={'设置'} top_rightView={<></>} />
          {isLogin && <Cell
            isLink
            renderIcon={<IconFont name="ac-bianjiziliaoxiugaimima-" style={{ marginRight: 5 }} size={40} />}
            title="资料修改"
            linkType="navigateTo"
            url="/pages/mine/components/mymaterial/index"
          />}
          <Cell
            isLink
            onClick={() => {
              setImgUrl(Xiaochengxu)
              modalRef.current.show()
            }}
            renderIcon={<IconFont name="ac-fenxiang" style={{ marginRight: 5 }} size={40} />}
            title="分享易搜索"
          />
          <Cell
            isLink
            onClick={() => {
              setImgUrl(GongZhongHao)
              modalRef.current.show()
            }}
            renderIcon={<IconFont name="ac-guanzhu" style={{ marginRight: 5 }} size={40} />}
            title="关注易搜索"
          />
          <Cell
            isLink
            onClick={() => {
              setImgUrl(Wechat)
              modalRef.current.show()
            }}
            renderIcon={<IconFont name="ac-lianxikefu" style={{ marginRight: 5 }} size={40} />}
            title="联系博主"
          />
          <Cell
            isLink
            renderIcon={<IconFont name="ac-guanyuyingyong" style={{ marginRight: 5 }} size={40} />}
            title="关于应用"
            linkType="navigateTo"
            url="/pages/mine/components/aboutapplications/index"
          />
          {isLogin && <Cell
            isLink
            renderIcon={<IconFont name="ac-tuichudenglu" style={{ marginRight: 5 }} size={40} />}
            title="退出登录"
            onClick={() => {
              Taro.clearStorage()
              getLoginStatus()
            }}
          />}
        </View>
      </View>
      <CusModal ref={modalRef} url={imgUrl} />
      <TabBar active={'mine'} />
    </View>
  )
}


export default Mine